'use strict';
var moment = require('moment');

var TODOLIST = require('../class/TodoList');
var USER = require('../class/User');
var wechat = require('../libs/wechat')();

var cursor = TODOLIST.find({
  query: {
    status: { '$ne': 1 },
    formId: { '$exists': true },
    notified: { '$ne': 'notified' },
    createAt: {
      '$gt': new Date(moment().add(-7, 'hours'))
    }
  },
  fileds: {
    // title: 1,
    createAt: 1,
    // formId: 1
  }
});

schedule.onMessage(function(key) {
  TODOLIST.detail(key).then(function(todo) {
    console.log('scheduled', todo);
    if (todo && todo.formId) {
      if ((todo.status == 1) || (todo.notified == 'notified')) return;

      USER.find(todo.creator).then(function(user) {
        if ((!user || !user.openid)) return;
        todo.create_at = todo.createAt;
        wechat.createNotify({ openid: user.openid, todo: todo });
      });
    }
  }).catch(e => console.log('get todo detail error:', key, e));
});

(function run() {
  cursor.hasNext(function(err, r) {
    if (r) {
      cursor.next(function(nextErr, todo) {

        if (nextErr) console.error(nextErr);
        else {
          var key = todo._id.toString();
          todo._id = key;
          schedule.exists(key, function(result) {
            if (result) return;

            schedule.setSchedule(key, moment(todo.createAt).add(5, 'hours'));
            // schedule.setSchedule(key, moment().add(15, 'seconds'));
          });
        }

        run();
      });
    }
  });
})();
